<template>
  <div class="flex">
    <el-menu class="h-[calc(100%-4px)] mr5" mode="horizontal" :ellipsis="false" >
      <el-sub-menu v-if="dropdownItems.length > 0" index="create">
        <template #title>
          <Icon icon="streamline-sharp:application-add" />
          <span>创建</span>
        </template>
        <el-menu-item v-for="(item, i) in dropdownItems" :key="i" :index="`create${i}`" @click="item.onClick">
          <Icon :icon="item.icon" />
          {{ item.label }}
        </el-menu-item>
      </el-sub-menu>
      <el-menu-item v-if="currentApp" index="save" @click="updateApp">
        <Icon icon="uil:save"/>
        <span>保存</span>
      </el-menu-item>
      <el-menu-item v-if="currentApp" index="remove" @click="removeCurrent">
        <Icon icon="ep:remove"/>
        <span>删除</span>
      </el-menu-item>
      <el-menu-item v-if="currentApp" index="viewSource" @click="viewSource">
        <Icon icon="hugeicons:source-code"/>
        <span>源码</span>
      </el-menu-item>
      <el-menu-item v-if="currentApp" index="reload" @click="reload">
        <Icon icon="mdi:reload"/>
        <span>发布</span>
      </el-menu-item>
      <el-menu-item v-if="currentApp" index="preview" @click="preview">
        <Icon icon="ep:view"/>
        <span>预览</span>
      </el-menu-item>
      <el-sub-menu v-if="currentApp" index="more">
        <template #title>
          <span>更多</span>
        </template>
        <el-menu-item index="root" @click="() => setBreadcrumbs('root')">
          <Icon icon="grommet-icons:domain" />
          <span>母页面</span>
        </el-menu-item>
        <el-menu-item index="login" @click="() => setBreadcrumbs('login')">          
          <Icon icon="iconoir:window-check" />
          <span>登录页面</span>
        </el-menu-item>
        <el-menu-item index="default-home" @click="() => setBreadcrumbs('default-home')">
          <Icon icon="bx:home" />
          <span>默认首页</span>
        </el-menu-item>
        <el-menu-item v-if="currentApp" index="import">
          <ElUpload :before-upload="importApp" :show-file-list="false">
            <Icon icon="uil:import"/>
            <span>导入</span>
          </ElUpload>
        </el-menu-item>
        <el-sub-menu v-if="currentApp" index="export">
          <template #title>
            <Icon icon="uil:export"/>
            <span>导出</span>
          </template>
          <el-menu-item index="json" @click="exportApp">
            <Icon icon="bi:filetype-json" />
            <span>json</span>
          </el-menu-item>
          <el-menu-item index="yml">          
            <Icon icon="bi:filetype-yml" />
            <span>yml</span>
          </el-menu-item>
          <el-menu-item index="property">
            <Icon icon="hugeicons:property-new" />
            <span>property</span>
          </el-menu-item>
        </el-sub-menu>
        <el-sub-menu v-if="currentApp" index="download">
          <template #title>
            <Icon icon="et:download"/>
            <span>下载</span>
          </template>
          <el-menu-item index="property">
            <Icon icon="bi:filetype-java" />
            <span>java工程</span>
          </el-menu-item>
        </el-sub-menu>
      </el-sub-menu>
    </el-menu>
    <el-segmented v-if="options.length > 0" v-model="active" :options="options">
      <template #default="{ item }">
        <div class="flex-center gap5px">
          <Icon :icon="item['icon']" />
          <span>{{ item['label'] }}</span>
        </div>
      </template>
    </el-segmented>
  </div>
</template>
<script setup lang="ts">
  import { ElSegmented, ElMenu, ElMenuItem, ElSubMenu, ElUpload } from 'element-plus';
  import { computed, ref, watch } from 'vue';
  import { get } from "@/utils/request"
  import { Icon } from '@/components/Icon';
  import { currentApp, active, breadcrumbs, getActiveOptions, getCreators, setBreadcrumbs, currentMicro } from '@/views/seed-dev';
  import feedback from '@/utils/feedback';
  import { AppSource } from '../../AppSource';
  import { open } from '@/components/Popup';
  import { clear } from '../../utils/AppClearUtil';
  import { appApi } from '@/api';
  import { useUserStore } from '@/store';

  const dropdownItems = computed(() => {
    const b = breadcrumbs.value
    const last = b && b.length > 0 ? b[b.length - 1] : void 0
    return getCreators(last?.type, last?.node?.data)
  })

  const options = ref([])
  watch(() => breadcrumbs.value, (val) => {
    if(val && val.length > 0) {
      const last = val[val.length - 1]
      options.value = getActiveOptions(last.type)
    } else {
      options.value = []
    }
  })

  let previewUrl
  async function preview() {
    const app = currentApp.value
    if(!previewUrl) {
      const res = await appApi.preview()
      console.log('preview res', res)
      previewUrl = res || window.location.origin
    }

    const userStore = useUserStore()
    const user = userStore.getLoginInfo()
    const owner = user?.username || ''
    const name = app.name
    
    window.open(`${previewUrl}?owner=${owner}&appName=${name}`, '_blank')
  }

  function viewSource() {
    open({title: `${currentApp.value.label}源码预览`, fullscreen: true}, AppSource)
  }

  async function updateApp() {
    feedback.loading('正在保存...')
    clear(currentApp.value)
    await appApi.update(currentApp.value)
    feedback.closeLoading()
    feedback.msgSuccess('保存成功')
  }

  async function reload() {
    const app = currentApp.value
    const owner = app.owner || ''
    const name = app.name
    feedback.loading('正在重新载入配置...')
    await get('reload', {owner, name})
    feedback.closeLoading()
    feedback.msgSuccess('载入成功')
  }

  function importApp(file: File) {
    var reader = new FileReader()
    reader.onload = (e) => {
      const { owner, name } = currentApp.value
      currentApp.value = JSON.parse(e.target.result as string)
      currentApp.value.owner = owner
      currentApp.value.name = name
    }
    reader.readAsText(file)
    return false
  }

  function exportApp() {
    const blob: Blob = new Blob([JSON.stringify(currentApp.value, null, 2)], {type: 'text/plain'})
    const a = document.createElement('a')
    a.setAttribute('download', `${currentApp.value.name}.json`)
    a.href = URL.createObjectURL(blob)
    a.click()
  }

  async function removeCurrent() {
    if(!breadcrumbs.value || breadcrumbs.value.length === 0) return

    const last = breadcrumbs.value[breadcrumbs.value.length - 1]
    // const node: TreeNode = treeRef.value?.getCurrentNode()
    switch(last.type) {
      case 'app':
        removeApp()
        break
      case 'action':
        // TODO
        break
      case 'home':
        removeHome(last.node.data.homeName)
        break
    }
  }

  async function removeApp() {
    await feedback.confirm(`确定要删除当前应用【${currentApp.value.label}】吗? 删除后不能恢复`)
    await appApi.remove(currentApp.value.name)
    currentApp.value = void 0
    currentMicro.value = void 0
    breadcrumbs.value = void 0
    feedback.msgSuccess('删除成功')
  }

  async function removeHome(homeName: string) {
    if(currentMicro.value) {
      const micro = currentApp.value.micros[currentMicro.value]
      const home = micro.homes[homeName]
      await feedback.confirm(`确定要删除首页【${home.label || home.name}】吗?`)
      delete micro.homes[homeName]
      if(Object.keys(micro.homes).length === 0) delete micro.homes
    } else {
      const home = currentApp.value.homes[homeName]
      await feedback.confirm(`确定要删除首页【${home.label || home.name}】吗?`)
      delete currentApp.value.homes[homeName]
      if(Object.keys(currentApp.value.homes).length === 0) delete currentApp.value.homes
    }
    const pre = breadcrumbs.value[breadcrumbs.value.length - 2]
    setBreadcrumbs(pre.type, pre.node)
  }
</script>
<style lang="less" scoped>
  :deep(.el-menu--horizontal.el-menu) {
    border: none
  }
</style>